import React from 'react';
import { browserHistory } from 'react-router';
import { connect } from 'dva';
import _ from 'lodash';
import * as authService from '../services/authService';
import Login from '../routes/LoginPage';
import Home from '../routes/HomePage';
import { Modal, Toast } from "antd-mobile";
import { CookiesProvider, withCookies } from 'react-cookie';
import {
  getOpenidByCode,
  loginByOpenid,
} from '../services/vipService';
import * as util from './util';

const OPENID_KEY = 'vipbang_web_kdhileonsqmax';
const VIPBANG_APPID = util.isLocal() ? 'wx223409e8c11e0312' : 'wx85e2114278f481d3';
const VIPBANG_SHOPID = util.isLocal() ? 'sixun_000032' : 'vipbang';
const COOKIE_AGE = 315360000;

class WechatLogin extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      message: '',
    };
  }

  doLogin = (openid) => {
    return new Promise((resolve, reject) => {
      if (this.props.location.pathname !== '/login') {
        let loginPromise;
        if (openid && openid.length) {
          loginPromise = loginByOpenid(openid);
        } else {
          loginPromise = authService.me();
        }
        loginPromise.then((data) => {
          if (_.get(data, 'data.shopId')) {
            if (_.get(data, 'data.status') === 1) {
              this.setState({
                message: '账号已禁用！',
              });
              resolve();
            } else {
              data.data.openid = data.data.openid || openid;
              this.props.dispatch({ type: 'auth/loginSuccess', payload: data.data });
              resolve(data.data);
            }
          } else {
            resolve();
          }
        }).catch(() => {
          resolve();
        });
      } else {
        resolve();
      }
    });
  }

  toWechat = () => {
    const redirectUri = encodeURI("http://wx.hy-bang.com/wx/oauthRedirect");
    // const redirectUri = encodeURI("http://localhost:7002/wx/oauthRedirect");
    const state = JSON.stringify({ host: window.location.host, shopId: VIPBANG_SHOPID, hash: '/' });
    const scope = 'snsapi_base';
    const timestamp = (new Date()).getTime();
    const oauthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${VIPBANG_APPID}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}&v=${timestamp}#wechat_redirect`;
    window.location.href = oauthUrl;
  }

  wechatLogin = () => {
    if (!util.isWechat()) {
      return;
    }

    const { openid, cookies, location: { query: { code } } } = this.props;
    const localOpenid = openid || cookies.get(OPENID_KEY);
    if (localOpenid && localOpenid.length) {
      this.props.dispatch({ type: 'auth/loginSuccess', payload: { openid: localOpenid } });
      this.doLogin(localOpenid);
    } else if (code && code.length) {
      getOpenidByCode(code, VIPBANG_SHOPID).then((result) => {
        if (result && result.data && result.data.openid) {
          this.props.dispatch({ type: 'auth/loginSuccess', payload: { openid: result.data.openid } });
          cookies.set(OPENID_KEY, result.data.openid, {
            maxAge: COOKIE_AGE,
          });
          this.doLogin(result.data.openid);
        }
      }).catch((error) => {
        console.error(error);
      });
    } else {
      this.toWechat();
    }
  }

  componentDidMount() {

    // const { isLogin } = this.props;
    // if (isLogin) {
    //   return;
    // }
    // Toast.loading('请稍候...', 3);
    // this.doLogin().then((user) => {
    //   if (this.isDemo()) {
    //     return;
    //   }
    //
    //   // 未发现登录用户，跳至微信登录
    //   if (!user || !user.shopId) {
    //     this.wechatLogin();
    //   }
    // });
  }

  isDemo = () => {
    return window.location.href.indexOf('hy-bang.com/demo') > 0;
  }

  render() {
    if (this.state.message) {
      return <h3 style={{ textAlign: 'center' }}>{this.state.message}</h3>;
    }
    if (this.props.isLogin) {
      if (this.props.location.pathname === '/') {
        return <Home />;
      }
      return this.props.children;
    }
    return <Login />;
  }
}


class WechatEntry extends React.Component {
  componentDidMount() {
    // http://wx.hy-bang.com/v3/
    window.location.href = "http://wx.hy-bang.com/v3/";
  }

  render() {
    return <div/>;
    // const CookieWechatLogin = withCookies(WechatLogin);
    // return (<CookiesProvider>
    //   <CookieWechatLogin {...this.props} />
    // </CookiesProvider>);
  }
}

function mapStateToProps(state, props) {
  return {
    isLogin: !!state.auth.currentUser.shopId,
    openid: state.auth.currentUser.openid,
  };
}

export default connect(mapStateToProps)(WechatEntry);
